"""
资源基类抽象
定义通用字段和方法，供所有资源模型继承
"""
from pydantic import BaseModel, Field
from typing import Optional, Dict, Any, List
from datetime import datetime
from enum import Enum


class ResourceStatus(str, Enum):
    """资源状态"""
    ACTIVE = "active"
    INACTIVE = "inactive"
    PENDING = "pending"
    DELETED = "deleted"
    SUSPENDED = "suspended"
    EXPIRED = "expired"


class ResourceBase(BaseModel):
    """
    资源基类
    
    所有资源模型都应该继承此类，包含通用字段
    """
    user_id: str = Field(..., description="所属用户ID（自动注入）")
    status: ResourceStatus = Field(default=ResourceStatus.ACTIVE, description="资源状态")
    tags: List[str] = Field(default_factory=list, description="标签列表")
    metadata: Dict[str, Any] = Field(default_factory=dict, description="元数据")
    created_at: datetime = Field(default_factory=datetime.utcnow, description="创建时间")
    updated_at: Optional[datetime] = Field(None, description="更新时间")


class ResourceInDB(ResourceBase):
    """
    数据库中的资源
    
    包含 _id 字段
    """
    id: str = Field(..., description="资源ID")
    
    class Config:
        from_attributes = True


class ResourceOut(ResourceBase):
    """
    返回给客户端的资源
    
    包含转换后的 id 字段
    """
    id: str = Field(..., description="资源ID")
    
    class Config:
        from_attributes = True


class ResourceCreate(BaseModel):
    """
    创建资源的基础模型
    
    不包含 user_id（自动注入）、created_at、updated_at
    """
    tags: List[str] = Field(default_factory=list, description="标签列表")
    metadata: Dict[str, Any] = Field(default_factory=dict, description="元数据")


class ResourceUpdate(BaseModel):
    """
    更新资源的基础模型
    
    所有字段都是可选的
    """
    status: Optional[ResourceStatus] = None
    tags: Optional[List[str]] = None
    metadata: Optional[Dict[str, Any]] = None


class PaginationQuery(BaseModel):
    """分页查询参数"""
    skip: int = Field(default=0, ge=0, description="跳过记录数")
    limit: int = Field(default=20, ge=1, le=100, description="返回记录数")
    sort_by: str = Field(default="created_at", description="排序字段")
    sort_order: int = Field(default=-1, description="排序顺序（1升序，-1降序）")


class PaginationResult(BaseModel):
    """分页查询结果"""
    total: int = Field(..., description="总记录数")
    skip: int = Field(..., description="跳过记录数")
    limit: int = Field(..., description="返回记录数")
    has_more: bool = Field(..., description="是否还有更多数据")
    
    @classmethod
    def from_query(cls, total: int, skip: int, limit: int):
        """从查询参数创建分页结果"""
        return cls(
            total=total,
            skip=skip,
            limit=limit,
            has_more=(skip + limit) < total
        )


class BatchOperation(BaseModel):
    """批量操作"""
    resource_ids: List[str] = Field(..., min_items=1, max_items=100, description="资源ID列表")


class BatchResult(BaseModel):
    """批量操作结果"""
    success_count: int = Field(..., description="成功数量")
    failed_count: int = Field(..., description="失败数量")
    failed_ids: List[str] = Field(default_factory=list, description="失败的资源ID列表")
    errors: Dict[str, str] = Field(default_factory=dict, description="错误信息（资源ID: 错误信息）")

